<template>
  <div class="app-container user">
    <!-- 筛选部分 -->
    <div class="app-container-hd">
      <div class="toolbar-search">
        <div class="table-top-button">
          <div>
            <el-button icon="el-icon-printer" type="primary" size="mini" @click="handlePrint">单据打印</el-button>
            <el-button icon="el-icon-download" type="primary" size="mini" @click="handleExport">导出数据</el-button>
            <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleClearBond">批量清空保证金</el-button>
            <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleUpdateAll">批量修改投标权限</el-button>
          </div>
          <div>
            <el-button v-if="showSearch" type="primary" @click="showSearch = false">收起<i class="el-icon-arrow-up el-icon--right" /></el-button>
            <el-button v-else type="primary" @click="showSearch = true">展开<i class="el-icon-arrow-down el-icon--right" /></el-button>
          </div>
        </div>
        <el-form v-if="showSearch" ref="searchParams" :model="searchParams" :inline="true" size="mini" @keyup.enter.native="handleSearch">
          <el-form-item label="会员号:" prop="number">
            <el-input v-model="searchParams.number" placeholder="会员号" style="width: 180px" />
          </el-form-item>
          <el-form-item label="手机号:" prop="phone">
            <el-input v-model="searchParams.phone" placeholder="手机号" style="width: 180px" />
          </el-form-item>
          <el-form-item label="姓名:" prop="name">
            <el-input v-model="searchParams.name" placeholder="用户姓名" style="width: 180px" />
          </el-form-item>
          <el-form-item label="备注:" prop="remarks">
            <el-input v-model="searchParams.remarks" placeholder="用户备注" style="width: 180px" />
          </el-form-item>
          <el-form-item label="状态:" prop="status">
            <el-select v-model="searchParams.status" placeholder="选择可用状态" clearable>
              <el-option :key="0" label="停用" :value="0" />
              <el-option :key="1" label="正常" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户组:" prop="group_id">
            <el-select v-model="searchParams.group_id" placeholder="选择用户组" clearable>
              <el-option label="注册用户" :value="0" />
              <el-option v-for="item in groupList" :key="item.group_id" :label="item.group_name" :value="item.group_id" />
            </el-select>
          </el-form-item>
          <div class="form-button">
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="handleSearch">筛选</el-button>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-refresh" @click="handleSearch('searchParams', 'reset')">重置</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>

      <!-- 表格部分 -->
      <div v-loading="$store.state.app.loading" class="table-main fixed">
        <div class="table-top-button">
          <el-button icon="el-icon-plus" type="primary" size="mini" @click="handleOpenModal(null)">新增</el-button>
        </div>
        <el-table
          row-key="user_id"
          highlight-current-row
          :data="listData"
          :border="true"
          :empty-text="$store.state.app.loading ? '正在加载数据' : null"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="48" fixed align="center" />
          <el-table-column prop="avatar_url" label="头像" width="50">
            <template slot-scope="item">
              <el-image
                style="width: 32px; height: 32px;margin-top: 8px;margin-left: -2px"
                :src="completionAvatar(item.row['avatar'])"
                fit="cover"
              ><div slot="error" class="image-slot"><i class="el-icon-picture-outline" /></div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="number" label="会员号" width="100" />
          <el-table-column prop="phone" label="手机号码" width="150" />
          <el-table-column prop="name" label="姓名" min-width="150">
            <template slot-scope="item">
              <span v-if="item.row.name">{{ item.row.name }}</span>
              <span v-else class="color-minor">匿名</span>
            </template>
          </el-table-column>
          <el-table-column prop="group" label="分组" width="150">
            <template slot-scope="item">
              <span v-if="item.row.group">{{ item.row.group.group_name }}</span>
              <span v-else class="color-minor">注册用户</span>
            </template>
          </el-table-column>
          <el-table-column prop="remarks" label="备注" width="150" />
          <el-table-column prop="can_bid" label="是否可参与投标" width="120">
            <template slot-scope="item">
              <el-tag v-if="item.row.extra.can_bid === 1" type="success" size="small">是</el-tag>
              <el-tag v-else type="info" size="small">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="extra.bond" label="保证金" width="150" />
          <el-table-column prop="is_admin" label="是否能发布商品" width="120">
            <template slot-scope="item">
              <el-tag v-if="item.row.is_admin === 1" type="success" size="small">是</el-tag>
              <el-tag v-else type="info" size="small">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="当前状态" width="80">
            <template slot-scope="item">
              <el-tag v-if="item.row.status === 1" type="success" size="small">正常</el-tag>
              <el-tag v-else type="danger" size="small">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
          <el-table-column prop="action" label="操作" min-width="100">
            <template slot-scope="item">
              <div class="button-group">
                <el-button type="text" size="mini" @click="handleOpenModal(item.row, true)">编辑
                </el-button>
                <el-button type="text" size="mini" @click="handleRowDelete(item.row)">删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="app-container-ft">
      <paginate :total="searchParams.total" :per-page="searchParams.per_page" :page="searchParams.page" @paginate-change="handleSearch" />
    </div>

    <!-- 数据编辑弹窗 -->
    <box-save
      v-if="showModal"
      :is-update="isUpdate"
      :item-data="itemData"
      :option="{ groupList: groupList }"
      @on-cancel-modal="acceptCancelModal"
    />
    <save-extra
      v-if="showExtra"
      :params="extraParams"
      @on-cancel-modal="acceptCancelModal"
    />

    <!-- 打印弹窗 -->
    <Print
      v-if="printModal"
      :print-data="printData"
      :tpl-id="tplId"
      :tpl-list="tplList"
      :cache-mark="cacheMark"
      @on-cancel-modal="acceptCancelModal"
    />

    <!-- Excel数据导出 -->
    <Export
      v-if="showExport"
      :field-list="exportFields"
      :data-list="dataList"
      @on-cancel-modal="acceptCancelModal"
    />
  </div>
</template>

<script>
import boxSave from './components/save'
import saveExtra from './components/saveExtra'
import Export from './components/export'
import Paginate from '@/components/Paginate/index'
import Print from '@/components/Print'
import { initial, paginate, info, destroy, updateAll } from '@/api/user'
import { fileUrl } from '@/utils/tools'
import { getPrintTplList } from '@/api/print-tpl'

export default {
  components: { Paginate, boxSave, Print, Export, saveExtra },
  data: function() {
    return {
      listData: [],
      groupList: null,
      itemData: null,
      isUpdate: false,
      showModal: false,
      showSearch: true,

      showExtra: false,
      extraParams: null,

      printModal: false,
      tplId: null,
      tplList: [],
      printData: null,
      cacheMark: null,

      showExport: false,
      exportFields: null,
      dataList: [],

      selected: [],
      searchParams: {
        created_at: null,
        user_id: null,
        phone: null,
        name: null,
        remarks: null,
        group_id: null,
        status: null,
        total: null,
        page: null,
        per_page: parseInt(process.env.VUE_APP_PER_PAGE)
      }
    }
  },
  mounted: function() {
    // 初始化方法
    this.initialize()
  },
  methods: {
    // 初始化数据列表
    initialize: function() {
      // 获取数据列表
      this.$store.commit('app/SET_LOADING', true)
      if (this.groupList === null) {
        initial(function(res) {
          if (res !== false) {
            this.listData = res[0].data
            this.searchParams.total = parseInt(res[0].total)
            this.searchParams.page = parseInt(res[0].current_page)
            this.searchParams.per_page = parseInt(res[0].per_page)
            this.groupList = res[1].data
          }
          this.$nextTick(function() {
            this.$store.commit('app/SET_LOADING', false)
          })
        }.bind(this), this.searchParams)
      } else {
        paginate(this.searchParams).then(res => {
          this.listData = res.data
          this.searchParams.total = parseInt(res.total)
          this.searchParams.page = parseInt(res.current_page)
          this.searchParams.per_page = parseInt(res.per_page)
          this.$nextTick(function() {
            this.$store.commit('app/SET_LOADING', false)
          })
        })
      }
    },
    // 根据条件筛选数据
    handleSearch: function(value, field) {
      // 重置表单数据
      if (field === 'reset') {
        this.searchParams.page = 1
        this.$refs[value].resetFields()
        // 页码参数变更
      } else if (field) {
        this.searchParams.page = 1
        this.searchParams[field] = value
      }
      this.initialize()
    },
    // 打开数据编辑窗口
    handleOpenModal: function(itemData, isUpdate = false) {
      this.itemData = itemData
      this.isUpdate = isUpdate
      this.$store.commit('app/SET_LOADING', true)
      if (this.isUpdate) {
        info(this.itemData['user_id']).then(res => {
          this.itemData = res.data
          this.showModal = true
          this.$store.commit('app/SET_LOADING', false)
        })
      } else {
        this.showModal = true
        this.$store.commit('app/SET_LOADING', false)
      }
    },
    // 关闭数据编辑窗口
    acceptCancelModal: function(modal, refresh = false) {
      if (refresh === true) {
        this.initialize()
      }
      this[modal] = false
    },
    handleSelectionChange: function(data) {
      const selected = []
      for (let i = 0; i < data.length; i++) {
        selected.push(data[i]['user_id'])
      }
      this.selected = selected
    },
    // 删除列表指定数据
    handleRowDelete: function(row) {
      this.$confirm('该操作将彻底删除该数据切无法恢复，确定要继续吗?', '提示', {
        distinguishCancelAndClose: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '请稍等...'
            destroy(row.user_id).then(function() {
              done()
              this.initialize()
              instance.confirmButtonLoading = false
              instance.confirmButtonText = '确定'
            }.bind(this)).catch(function() {
              instance.confirmButtonLoading = false
              instance.confirmButtonText = '确定'
            })
          } else {
            done()
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
          }
        }
      })
    },
    handleClearBond() {
      if (this.selected.length <= 0 && (!this.searchParams.created_at || this.searchParams.created_at.length !== 2)) {
        this.$message.warning('请选择要操作的数据，或选择时间范围'); return false
      } else {
        const params = { ...this.searchParams, bond: 0 }
        if (this.selected.length > 0) {
          params.user_ids = this.selected
        }
        this.$confirm('该操作无法恢复，确定要继续吗?', '提示', {
          distinguishCancelAndClose: false,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '请稍等...'
              updateAll(params).then(function() {
                done()
                this.initialize()
                instance.confirmButtonLoading = false
                instance.confirmButtonText = '确定'
              }.bind(this)).catch(function() {
                instance.confirmButtonLoading = false
                instance.confirmButtonText = '确定'
              })
            } else {
              done()
              instance.confirmButtonLoading = false
              instance.confirmButtonText = '确定'
            }
          }
        })
      }
    },
    handleUpdateAll() {
      if (this.selected.length <= 0 && (!this.searchParams.created_at || this.searchParams.created_at.length !== 2)) {
        this.$message.warning('请选择要操作的数据，或选择时间范围'); return false
      } else {
        const params = { ...this.searchParams }
        if (this.selected.length > 0) {
          params.user_ids = this.selected
        }
        this.extraParams = params
        this.showExtra = true
      }
    },
    handlePrintData(data) {
      const lists = data.map((e, index) => {
        return {
          ...e,
          index: index + 1
        }
      })
      console.log(lists)
      return {
        lists: lists
      }
    },
    // 单据打印
    handlePrint() {
      if (this.selected.length <= 0 && (!this.searchParams.created_at || this.searchParams.created_at.length !== 2)) {
        this.$message.warning('请选择要打印的数据，或选择时间范围'); return false
      } else {
        this.cacheMark = 'print-user-list'
        this.$store.commit('app/SET_LOADING', true)
        this.tplId = parseInt(localStorage.getItem(this.cacheMark))
        const params = { ...this.searchParams, is_export: 1 }
        if (this.selected.length > 0) {
          params.user_ids = this.selected
        }
        Promise.all([
          paginate(params),
          getPrintTplList({ mode: 'user_list' })
        ]).then(res => {
          if (res !== false) {
            console.log(res)
            this.printData = this.handlePrintData(res[0].data)
            this.tplList = res[1].data
          }
          this.printModal = true
          this.$nextTick(function() {
            this.$store.commit('app/SET_LOADING', false)
          })
        })
      }
    },
    handleExport: function() {
      if (this.selected.length <= 0 && (!this.searchParams.created_at || this.searchParams.created_at.length !== 2)) {
        this.$message.warning('请选择要导出的数据，或选择时间范围')
      } else {
        this.exportFields = JSON.parse(localStorage.getItem('export-user-fields'))
        this.$store.commit('app/SET_LOADING', true)
        const params = { ...this.searchParams, is_export: 1 }
        if (this.selected.length > 0) {
          params.goods_ids = this.selected
        }
        paginate(params).then(res => {
          this.dataList = this.handlePrintData(res.data).lists
          this.showExport = true
          this.$nextTick(function() {
            this.$store.commit('app/SET_LOADING', false)
          })
        })
      }
    },
    // 处理用户头像
    completionAvatar: function(value) {
      return fileUrl(value, 'image', 200, 200)
    }
  }
}
</script>
<style lang="scss">
.user .el-table {
  th {
    height: 48px;
    line-height: 48px;
  }
  td {
    height: 47.5px;
    color: #909399;
    line-height: 35px;
  }
  .el-table__expanded-cell .el-table {
    margin-left: 20px;
  }
}
</style>

<style lang="scss" scoped>
.el-image {
  padding: 0;
  border: none;
}

.table-top-button {
  display: flex;
  padding-bottom: 10px;
  justify-content: space-between;
}
</style>
